package zheng.mockit.plugin.http;

import org.eclipse.jetty.server.Server;
import zheng.mockit.plugin.AbstractServer;
import zheng.mockit.plugin.http.message.MockitHttpResponseMessage;

/**
 * Created by zcz on 16-7-29.
 */
public class MockitHttpServer extends AbstractServer {

    private Server server;

    public MockitHttpServer() {
    }

    @Override
    public void startup() {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                server = new Server(configuration.getInt("port"));
                server.setHandler(new MockitHttpServerHandler(messageHandler));
                try {
                    server.start();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        thread.start();
        try {
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void shutdown() {
        try {
            server.stop();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public void sendResponse(Object message) {
        if (message instanceof String || message instanceof Boolean || message instanceof Integer ||
                message instanceof Double || message instanceof Long) {
            MockitHttpResponseMessage responseMessage = new MockitHttpResponseMessage();
            responseMessage.setStatusCode(200);
            responseMessage.setContent(message.toString());
            messageHandler.sendMessage2Plugin(responseMessage);
        } else {
            messageHandler.sendMessage2Plugin(message);
        }
    }
}
